package com.tsinghuabigdata.edu.ddmath.module.login.view;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Order;
import com.mobsandgeeks.saripaar.annotation.Pattern;
import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.activity.RoboForToolBarActivity;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.commons.http.InformMapping;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.module.login.LoginModel;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.KeyboardUtil;
import com.tsinghuabigdata.edu.ddmath.util.ValidatorUtils;
import com.tsinghuabigdata.edu.ddmath.view.MyProgressDialog;
import com.tsinghuabigdata.edu.utils.SetTimeout;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 找回密码
 * Created by Administrator on 2016/12/14.
 */

public class BindMobileActivity extends RoboForToolBarActivity implements View.OnClickListener {

    @ViewInject(R.id.bt_done)
    private Button btDone;


    @Order(1)
    @NotEmpty(trim = true, message = "手机号不能为空", sequence = 1)
    @Pattern(regex = ValidatorUtils.MOBILE_REGEX, message = "请输入正确手机号", sequence = 2)
    @ViewInject(R.id.et_phone)
    private EditText etPhone;

    @Order(2)
    @NotEmpty(trim = true, message = "验证码不能为空", sequence = 1)
    @ViewInject(R.id.et_verifycode)
    private EditText etVerifycode;


    @ViewInject(R.id.bt_verifycode)
    private Button btVerifycode;

    private Validator mValidator;

    private ProgressDialog progressDialog;

    private SetTimeout mSetTimeout;
    private final int mMaxTime = AppConst.CODE_MAX_TIME;

    private boolean isTimeCountStop;
    private Context context;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_bindmobile;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        context = this;

        initView();
        initData();
        initValidator();

    }

    private void initValidator() {
        mValidator = new Validator(this);
        mValidator.setValidationListener(new Validator.ValidationListener() {
            @Override
            public void onValidationSucceeded() {
                KeyboardUtil.hidInput((Activity) context);
                if (!ValidatorUtils.validateMobile(etPhone.getText().toString().trim())) {
                    etPhone.setError("请输入正确的手机号");
                    return;
                }
                //全部验证完输入，开始请求找回密码
                bindMobile();
            }

            @Override
            public void onValidationFailed(List<ValidationError> errors) {
                for (ValidationError error : errors) {
                    ((EditText) error.getView()).setError(error.getFailedRules().get(0).getMessage(context));
                }
            }
        });
    }

    private void initView() {
        setTitle("绑定手机号");
        setBarTextcolor(R.color.white);
        setUserBarBackgroud(true);

        //listener
        btDone.setOnClickListener(this);
        btVerifycode.setOnClickListener(this);

        progressDialog = new MyProgressDialog(context);
    }

    private void initData() {

    }

    @Override
    public void onLeftClick() {
        super.onLeftClick();
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_done:
                mValidator.validate();
                break;
            case R.id.bt_verifycode:
                sendVerifycode();
                break;
        }
    }

    private void bindMobile() {
        String accessToken = AccountUtils.getLoginUser().getAccessToken();
        String accountId = AccountUtils.getLoginUser().getAccountId();
        final String phone = etPhone.getText().toString().trim();
        String validcode = etVerifycode.getText().toString().trim();

//        accessToken = "B9237AA20BC14C67804156AD64BF0E1F";
//        accountId="B9237AA20BC14C67804156AD64BF0E1F";
        progressDialog.setMessage("手机绑定中...");
        progressDialog.show();
        new LoginModel().bindMobile(accessToken, accountId, phone, validcode, new RequestListener<Object>() {
            @Override
            public void onSuccess(Object res) {
                progressDialog.dismiss();
                AlertManager.toast(context, "绑定成功");

                UserDetailinfo userdetailInfo = AccountUtils.getUserdetailInfo();
                userdetailInfo.setPhone( phone );
                AccountUtils.setUserdetailInfo( userdetailInfo );
                finish();
            }

            @Override
            public void onFail(HttpResponse response, Exception ex) {
                progressDialog.dismiss();
                if (!TextUtils.isEmpty(response.getInform())) {
                    AlertManager.toast(context, InformMapping.getInstance().get(response.getInform()));
                } else {
                    AlertManager.showErrorInfo(context, ex);
                }
            }
        });
    }

    private void sendVerifycode() {
        String phone = etPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            etPhone.setError("手机号不能为空");
            return;
        } else if (!ValidatorUtils.validateMobile(phone)) {
            etPhone.setError("请输入正确手机号");
            return;
        }
        //start get verifycode from server
        progressDialog.setMessage("获取验证码...");
        progressDialog.show();
        String type = "binding"; //操作类型(register, passwdRetrieve,binding)
        new LoginModel().getVerifycode(phone, type, new RequestListener<String>() {
            @Override
            public void onSuccess(String res) {
                progressDialog.dismiss();
                AlertManager.toast(context, "验证码已发送至手机，请查看");
                getVerifycodeSuccess();
            }

            @Override
            public void onFail(HttpResponse response, Exception ex) {
                progressDialog.dismiss();
                if (response.getCode() == 21109) {
                    AlertManager.toast(context, "该手机号未注册");
                } else {
                    AlertManager.showErrorInfo(context, ex);
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSetTimeout != null) {
            Log.d("recover", "onDestroy: ");
            isTimeCountStop = true;
            mSetTimeout.cancel();
        }
    }

    private void getVerifycodeSuccess() {
        btVerifycode.setEnabled(false);
        btVerifycode.setText(mMaxTime + getString(R.string.resend_verifycode));

        mSetTimeout = new SetTimeout(mMaxTime, TimeUnit.SECONDS, 1);
        mSetTimeout.setHandler(new SetTimeout.SetTimeoutHandler() {
            @Override
            public void handler(final int current) {
                if (isTimeCountStop) {
                    return;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int remain = mMaxTime - current - 1;
                        if (remain > 0) {
                            btVerifycode.setText(remain + getString(R.string.resend_verifycode));
                        } else {
                            btVerifycode.setText(getText(R.string.send_verifycode));
                            btVerifycode.setEnabled(true);
                        }
                    }
                });
            }
        });
        mSetTimeout.start();
    }
}
